
/**
 * Domain Url for images of flags of the nations.
 * @type {string}
 * @const
 */
var FLAG_URL = 'http://www.google.com/images/flags/small/';

/**
 * Domain Url for images of flags of the nations.
 * @type {string}
 * @const
 */
var BIG_FLAG_URL = 'http://www.google.com/images/flags/';

/**
 *
 */
function getLocation(venueId) {
  return MESSAGES['VC_' + venueId] || '';
}


/**
 *
 */
function getIsoCode(teamId) {
  return TEAMS[teamId].isoCode ||  '';
}

/**
 *
 */
function getTeamName(teamId) {
  return TEAMS[teamId].name || '';
}

/**
 *
 */
function getFlagUrl(teamId) {
  return  '<span title="' + getTeamName(teamId) + '"><img src="' +
      FLAG_URL + getIsoCode(teamId) + '.gif"></span>';
}

/**
 *
 */
function getBigFlagUrl(teamId) {
  return  '<span title="' + getTeamName(teamId) + '"><img src="' +
      BIG_FLAG_URL + TEAMS[teamId].id + '.gif"></span>';
}

/**
 * Gets event time in 'hrs : mins' format.
 * @param {Date} eventDate Date for which time is to be calculated.
 * @return {string} Returns time in 'hrs : mins' format.
 */
function getTime(eventDate) {
  var hrs = eventDate.getHours();
  if (hrs < 10) {
    hrs = '0' + hrs;
  }
  var mins = eventDate.getMinutes();
  if (mins < 10) {
    mins = '0' + mins;
  }
  return hrs + ':' + mins;
}

/**
 * Returns the given date as format specified in locale.
 * @param {Object} date Date to be changed into locale format.
 * @return {string} Locale specific date format.
 */
function getDateInLocaleFormat(date) {
  var day = date.getDate();
  return '%mmmm% %d%, %yyyy%'.replace('%d%', day)
      .replace('%mmmm%', MESSAGES['M_' + date.getMonth()])
      .replace('%m%', date.getMonth())
      .replace('%yyyy%', date.getFullYear());
}

/**
 * Pour the data in template string.
 * @param {Object} datObject The data object to be filled in template string.
 * @return {string} The new string created from template string and filled
 *     with the given data.
 */
String.prototype.supplant = function(datObject) {
  return this.replace(/{([^{}]+)}/g,
    function(match, firstSubMatch) {
      var replace = datObject[firstSubMatch];
      return (typeof replace === 'string' || typeof replace === 'number') ?
          replace : match;
    });
};

/**
 * Generates duration string for the given date.
 * Its format YYYYMMDDTHHMMSSZ/YYYYMMDDTHHMMSSZ.
 * @param {Date} date The date object.
 * @return {string} The formatted string to use in google calendar template.
 */
function getCalendarDuration(date) {
  var endDate = new Date();
  var MATCH_DURATION = 120 * 60 * 1000;
  endDate.setTime(date.getTime() + MATCH_DURATION);
  return getUTCString(date) + '/' + getUTCString(endDate);
}

/**
 * Returns two digit string for the given number.
 */
function addZeroPrefix(number) {
  return ((number < 10) ? '0' : '' ) + number;
}

/**
 *
 */
function addToCalendar(matchNumber) {
  var match = getMatchByMatchNumber(matchNumber);
  if (!match) {
    return;
  }
  var formElement = document.getElementById('calender-' + matchNumber);
  if (formElement) {
    formElement.submit();
  }
}

/**
 * Get UTC time format.
 * Its format YYYYMMDDTHHMMSSZ/YYYYMMDDTHHMMSSZ.
 * @param {Date} date The date object.
 * @return {string} The formatted string.
 */
function getUTCString(date) {
  return [
    date.getUTCFullYear(),
    addZeroPrefix(date.getUTCMonth() + 1),
    addZeroPrefix(date.getUTCDate()),
    'T',
    addZeroPrefix(date.getUTCHours()),
    addZeroPrefix(date.getUTCMinutes()),
    addZeroPrefix(date.getUTCSeconds()),
    'Z'
  ].join('')
}

/**
 * Generates html of the match's fixture of the current league
 * and returns the string.
 * @param {Object} item Object of the current event.
 * @return {string} Html of the current event.
 */
function createMatchSchedule(item) {
  if (!item.team1id || !item.team2id) {
    return '';
  }
  var team1Id = item.team1id, team2Id = item.team2id;
  var matchNumber = item.matchnumber;
  var tplHtml = document.getElementById('tpl-match').value;
  var tplData = {
    matchNumber: matchNumber,
    team1: item.team1,
    team2: item.team2,
    time: getTime(new Date(item.date)),
    dateLocaleFormat: getDateInLocaleFormat(new Date(item.date)),
    venue: item.venue,
    city: item.city,
    flag1: '',
    flag2: '',
    duration: getCalendarDuration(new Date(item.date)),
    location: item.venue + ', ' + item.city
  };
  if (team1Id) {
    tplData['team1'] = getTeamName(team1Id);
    tplData['flag1'] = getFlagUrl(team1Id);
  }
  if (team2Id) {
    tplData['team2'] = getTeamName(team2Id);
    tplData['flag2'] = getFlagUrl(team2Id);
  }

  return tplHtml.supplant(tplData);
};

function getMatchByMatchNumber(matchNumber) {
  var item, index;
  var length = feedData.length;
  for (index = 0; index < length; index++) {
    item = feedData[index];
    if (item.matchnumber == matchNumber) {
      return item;
    }
  }
  return null;
}

function waveThis(matchNumber, action) {
  var match = getMatchByMatchNumber(matchNumber);
  var match = getMatchByMatchNumber('' + matchNumber);
  if (!match) {
    return;
  }
  // Set the title of the new wave.
  var titleElement = document.getElementById('title-' + matchNumber);
  titleElement.value = (action == 'party' ? 'Party' : 'Match' ) +
      ' Wave: ' + match.team1 + ' vs ' + match.team2;
  // Set the url of the new wave.
  var urlElement = document.getElementById('url-reference-' + matchNumber);
  var urlValue = urlElement.value;
  var index = urlValue.indexOf('&action=');
  if (index != -1) {
    // Remove the previous action.
    urlValue = urlValue.substring(0, index);
  }
  urlElement.value = urlValue + '&action=' + action;
  var formElement = document.getElementById('wave-this-' + matchNumber);
  window.open('','google');
  formElement.action = "https://wave.google.com/wave/wavethis";
  formElement.target = 'google';
  formElement.submit();
}

/**
 * Returns true if the passed event....
 */
function isValidDateRange(itemDate) {
  var today = new Date();
  var firstMatchDate = new Date('Fri Jun 11 2010 19:30:00 GMT+0530');
  var referenceTime = Math.max(today.getTime(), firstMatchDate.getTime());
  var oneDay = 24 * 60 * 60 * 1000;
  var noOfDays = Math.ceil((itemDate.getTime() - referenceTime) / oneDay);
  return (noOfDays > -1) && (noOfDays < 6)

}
/**
 * Calcuates the difference between two dates.
 * @param {Object} date1 first date as date object.
 * @param {Object} date2 second date as date object.
 * @return {number} number of days.
 */
function getDateDiff(date1, date2) {
  var oneDay = 24 * 60 * 60 * 1000;
  var noOfDays = Math.ceil((date2.getTime() - date1.getTime()) / oneDay);
  return noOfDays;
}

/**
 * Returns whether the match item needs to be rendered or not.
 * @param {Object} item The match event.
 * @return {boolean} Return true if the item could be rendered, else false.
 */
function isRender(item) {
  return item.team1id && item.team2id && isValidDateRange(new Date(item.date));
}

/**
 * Renders the UI for the landing page for recent upcoming events.
 * @param {string} parentId The parent element id.
 */
function renderUI(parentId) {
  var index, html = [], item;
  var length = feedData.length;
  for (index = 0; index < length; index++) {
    item = feedData[index];
    if (isRender(item)) {
      html.push('<div class="match">' + createMatchSchedule(item) + '</div>');
    }
  }
  document.getElementById(parentId).innerHTML = html.join('');
}

/**
 * Get events by group name.
 */
function getEventsByGroup(group) {
  var index, item, groupItems = [];
  var length = feedData.length;
  for (index = 0; index < length; index++) {
    item = feedData[index];
    if (item.group && item.group == group) {
      groupItems.push(item);
    }
  }
  return groupItems;
}

/**
 * Get content for one event.
 */
function getHtmlForEvent(item) {
  //console.log(item);
  if (!item.team1id || !item.team2id) {
    return '';
  }
  item.status = parseInt(item.status, 10);
  var team1Id = item.team1id, team2Id = item.team2id;
  var matchNumber = item.matchnumber;
  var tplHtml = document.getElementById('tpl-one-match').value;
  var tplData = {
    matchNumber: matchNumber,
    team1: item.team1,
    team2: item.team2,
    time: getTime(new Date(item.date)),
    matchDate: new Date(item.date).getTime(),
    dateLocaleFormat: getDateInLocaleFormat(new Date(item.date)),
    venue: item.venue,
    flag1: '',
    flag2: '',
    duration: getCalendarDuration(new Date(item.date)),
    location: item.venue + ', ' + item.city,
    team1Score: item.team1score || 0,
    team2Score: item.team2score || 0,
    dateStyle: item.status ? 'none' : '',
    scoreStyle: item.status ? '' : 'none'
  };
  if (team1Id) {
    tplData['team1'] = getTeamName(team1Id);
    tplData['flag1'] = getFlagUrl(team1Id);
  }
  if (team2Id) {
    tplData['team2'] = getTeamName(team2Id);
    tplData['flag2'] = getFlagUrl(team2Id);
  }
  //console.log(tplData);
  return tplHtml.supplant(tplData);
}

/**
 *
 */
function getGroupContent(groupName, groupItems) {
  var tplHtml = document.getElementById('tpl-group').value;
  var matchesHtml = [];
  var tplData = {groupName: groupName};
  var length = groupItems.length;
  for (index = 0; index < length; index++) {
    matchesHtml.push(getHtmlForEvent(groupItems[index]));
  }
  tplData['matches'] = matchesHtml.join('');
  return tplHtml.supplant(tplData);
}

/**
 * Renders the UI for the landing page by groups.
 * @param {string} parentId The parent element id.
 */
function renderByGroups(parentId) {
  var html = [], groupName;
  var index, groupItems;
  var length = GROUPS.length;
  for (index = 0; index < length; index++) {
    groupName = GROUPS[index];
    groupItems = getEventsByGroup(groupName);
    if (groupItems && groupItems.length) {
      html.push(getGroupContent(groupName, groupItems));
    }
  }
  document.getElementById(parentId).innerHTML = html.join('');
}

/**
 * Calculate width.
 */
function getWidthForPrediction(value, total) {
  var TOTAL_WIDTH = 150;
  return value / total * TOTAL_WIDTH;
}

/**
 * Render content for one prediction.
 */
function renderPrediction(matchId, predict) {
  //if (!predict.team1 || !predict.team2 || !predict.draw) {
  //  return;
  //}
  var match = getMatchByMatchNumber(matchId);
  if (!match) {
    return;
  }
  var tplHtml = document.getElementById('tpl-one-prediction').value;
  var targetElement = document.getElementById('statistic-' + matchId);
  var team1Score = predict.team1 || 0;
  var team2Score = predict.team2 || 0;
  var drawScore = predict.draw || 0;
  var totalScore = (team1Score + team2Score + drawScore) || 1;
  var tplData = {
    matchId: matchId,
    team1: team1Score,
    team2: team2Score,
    draw: drawScore,
    team1Width: getWidthForPrediction(team1Score, totalScore),
    team2Width: getWidthForPrediction(team2Score, totalScore),
    drawWidth: getWidthForPrediction(drawScore, totalScore),
    team1Flag: getFlagUrl(match.team1id),
    team2Flag: getFlagUrl(match.team2id)
  };
  if (targetElement) {
    targetElement.innerHTML = tplHtml.supplant(tplData);
  }
}

/**
 * Renders the UI for the predictions section.
 */
function renderPredictions() {
  var html = [], groupName;
  var key, groupItems;
  for (key in predictions) {
    renderPrediction(key, predictions[key]);
  }
}


/**
 * The function called on load of the page.
 */
function init() {
  //renderUI('main-content');
  renderByGroups('main-content');
  renderPredictions();
}
